// 使用路由的步骤
// 1.导入包
import Vue from 'vue'
import VueRouter from 'vue-router'
const Login = () => import('../views/login/login.vue')
const Layout = () => import('../views/layout/layout.vue')
const Atical = () => import('../views/articals/atical.vue')
const Images = () => import('../views/images/images.vue')
const Page404 = () => import('../views/page404/page404.vue')
const Edit = () => import('../views/articals/edit.vue')
const addAtical = () => import('../views/articals/add.vue')
const Comments = () => import('../views/comments/comments.vue')
const Fans = () => import('../views/fans/fans.vue')
const Settings = () => import('../views/settings/settings.vue')
const Home = () => import('../views/home/home.vue')
// 2.使用插件
Vue.use(VueRouter)
// 3.创建路由对象
const routes = [
  {
    path: '/',
    component: Layout,
    children: [
      // 文章管理
      {
        path: '/atical',
        component: Atical,
        meta: {
          title: '文章管理'
        }
      },
      // 素材管理
      {
        path: '/images',
        component: Images,
        meta: {
          title: '素材管理'
        }
      },
      // 动态路由
      {
        path: '/edit/:id',
        component: Edit,
        meta: {
          title: '编辑文章'
        }
      },
      // 添加文章
      {
        path: '/addatical',
        component: addAtical,
        meta: {
          title: '发布文章'
        }
      },
      // 评论管理
      {
        path: '/comments',
        component: Comments,
        meta: {
          title: '评论管理'
        }
      },
      // 粉丝管理
      {
        path: '/fans',
        component: Fans,
        meta: {
          title: '粉丝管理'
        }
      },
      // 个人设置
      {
        path: '/settings',
        component: Settings,
        meta: {
          title: '个人设置'
        }
      },
      {
        path: '/home',
        component: Home
      }
    ]
  },
  // 登录页面
  {
    path: '/login',
    component: Login,
    meta: {
      title: '登录'
    }
  },
  {
    path: '*',
    component: Page404
  }
]
const router = new VueRouter({
  routes
})
// 路由导航守卫
router.beforeEach((to, from, next) => {
  // （1）.设置页面标题
  if (to.meta.title) {
    document.title = to.meta.title
  } else {
    document.title = '黑马头条'
  }
  // （2）.需要token值的页面
  const list = ['/', '/atical', 'comments', 'images', 'addatical', '/fans', 'settings']
  if (list.includes(to.path)) {
    // （3）.获取token值
    const tokenStr = localStorage.getItem('tokenStr')
    if (tokenStr) {
      next()
    } else {
      next('/login')
    }
  } else {
    next()
  }
})
// 4.导出路由对象
export default router
